#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangByglmgzzzPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_byglmgzzz_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "巴音郭楞蒙古自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['巴音郭楞蒙古自治州人民政府', "", "http://www.xjbz.gov.cn/xjbz/bzbf/zfxxgk_zzzwj_list.shtml"],
            ['巴音郭楞蒙古自治州人民政府', "", "http://www.xjbz.gov.cn/xjbz/bzg/zfxxgk_zzzwj_list.shtml"],
            ['库尔勒市人民政府', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c110144/zwgk_gfxwjk.shtml"],
            ['库尔勒市发展和改革委员会(粮食和物资储备局)', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111511/zwgk_list.shtml"],
            ['库尔勒市科学技术局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111513/zwgk_list.shtml"],
            ['库尔勒市民政局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111516/zwgk_list.shtml"],
            ['库尔勒市人力资源和社会保障局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111519/zwgk_list.shtml"],
            ['库尔勒市财政局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111518/czzj.shtml"],
            ['库尔勒市商工局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111514/zwgk_list.shtml"],
            ['库尔勒市市场监督管理局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111536/zwgk_list.shtml"],
            ['库尔勒市农业农村局', "库尔勒市", "https://www.xjkel.gov.cn/xjkrls/c111526/zwgk_list.shtml"],
            ['轮台县人民政府', "轮台县", "http://www.xjlt.gov.cn/xjltx/c110366/zfxxgk.shtml"],
            ['尉犁县人民政府', "尉犁县", "https://www.yuli.gov.cn/xjylx/c110937/zfxxgk_table.shtml"],
            ['尉犁县财政局', "尉犁县", "https://www.yuli.gov.cn/xjylx/c111260/zfxxgk.shtml"],
            ['尉犁县人力资源和社会保障局', "尉犁县", "https://www.yuli.gov.cn/xjylx/c111261/zfxxgk.shtml"],
            ['且末县人民政府', "且末县", "https://www.xjqmx.gov.cn/xjqmx/c118534/zfxxgk_qmzfwj.shtml"],
            ['若羌县人民政府', "若羌县", "https://www.xjrq.gov.cn/rqxrmzf/c108622/zfxxgk_gknrz.shtml"],
            ['若羌县财政局', "若羌县", "https://www.xjrq.gov.cn/rqxrmzf/c108704/zfxxgk_gknrz_2.shtml"],
            ['若羌县商工局', "若羌县", "https://www.xjrq.gov.cn/rqxrmzf/c108705/zfxxgk_gknrz_2.shtml"],
            ['若羌县文广局', "若羌县", "https://www.xjrq.gov.cn/rqxrmzf/c108714/zfxxgk_gknrz.shtml"],
            ['若羌县民政局', "若羌县", "https://www.xjrq.gov.cn/rqxrmzf/c108723/zfxxgk_gknrz.shtml"],
            ['焉耆县人民政府', "焉耆县", "https://www.xjyq.gov.cn/xjyqx/c116452/zfxxgk_table.shtml"],
            ['和静县人民政府', "和静县", "https://www.xjhj.gov.cn/xjhjx/c110819/zwgk_table.shtml"],
            ['和静县民政局', "和静县", "https://www.xjhj.gov.cn/xjhjx/c110788/zwgk_table.shtml"],
            ['和静县农业农村局', "和静县", "https://www.xjhj.gov.cn/xjhjx/c110797/zwgk_table.shtml"],
            ['和硕县人民政府', "和硕县", "https://www.xjhs.gov.cn/xjhsx/c110583/zwgk_table.shtml"],
            ['博湖县人民政府', "博湖县", "https://www.xjbh.gov.cn/xjbhx/c115477/zfxxgk.shtml"],
            ['博湖县文化体育广播电视和旅游局', "博湖县", "https://www.xjbh.gov.cn/xjbhx/c109959/zfxxgk.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
                "//div[@class='table-main' or @class='table-responsive' or @class='govnewslista2353']//td//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='table-main' or @class='zfxxgk_right']//dd//a[contains(@href, 'htm') or @title]/ancestor::dd[string-length(string(.))>=5] |"
                "//tr//td[@class]//a[contains(@href, 'htm') or @title]/ancestor::td[string-length(string(.))>=5] |"
                "//div[@class='content' or @class='zfxxgk_right']//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5] |"
                "//div[@class]/ul[@class]//li//a[contains(@href, 'htm') or @title]/ancestor::li[string-length(string(.))>=5]"):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            if 'list.shtml' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_byglmgzzz_policy".split())
